package main

import (
	"flag"
	"fmt"
	"lark/consts"
	"lark/proto"
	"lark/util"
	"net"
	"sync"
	"time"

	"github.com/dchest/uniuri"
)

var serviceName = "lark-bench-service"

func main() {
	cNum := flag.Int("concurrence_num", 100, "并发数")
	tNum := flag.Int("task_num", 100, " 每个并发的任务数量")
	flag.Parse()

	fmt.Printf("并发数:%d, 每个并发任务数量:%d \n", *cNum, *tNum)

	begin := time.Now()

	var wg = new(sync.WaitGroup)

	for i := 0; i < *cNum; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < *tNum; j++ {
				requestOnce("tcp", "127.0.0.1:12311")
			}
		}()
	}

	wg.Wait()
	fmt.Printf("use time:%s \n", time.Since(begin))
}

func requestOnce(network string, addr string) {
	conn, err := net.Dial(network, addr)
	util.PanicErr(err)

	p := proto.NewlarkProtoV2(conn, time.Second*300, time.Second*300)
	defer p.Close()

	for i := 0; i < 1; i++ {
		begin := time.Now()

		code := uniuri.New()
		err = p.Write(consts.Lc2lcpTagTaskReq, []byte(code), []byte(serviceName))
		if err != nil {
			util.PanicErr(err)
			return
		}

		tag, payload, err := p.Read()
		if err != nil {
			fmt.Println(code)
			util.PanicErr(err)
			return
		}

		if tag != consts.Lcp2lcTaskRespOK {
			util.PanicErr(fmt.Errorf("wrong tag. %d", tag))
			return
		}

		if x := string(proto.SplitPayload(payload)[0]); x != code {
			util.PanicErr(fmt.Errorf("want:%s, get:%s", code, x))
		}

		if d := time.Since(begin); d > time.Second {
			fmt.Printf("code:%s, use time:%s \n", code, d)
		}

	}

}
